/**
 * @authors tanqichao
 * @date    2017-06-07 13:59:27
 * @module  互动创意包
 */

import * as createInteractiveService from '../services/createInteractive';
import { browserHistory } from 'dva/router';
import pathToRegexp from 'path-to-regexp';
import { message } from 'antd';
import moment from 'moment';

export default {
  namespace: 'createInteractive',
  state: {
    createLoading: false,
    action: ""
  },
  reducers: {
    save(state, action) {
      return {
        ...state,
        ...action.payload
      }
    },
    setLoading(state, action) {
      return {
        ...state,
        ...action.payload
      }
    },
    setAction(state, action) {
      return {
        ...state,
        ...action.payload
      }
    }
  },
  effects: {
    *submit({ payload }, { call, put }) {
      const { data } = yield call(createInteractiveService.submit, { payload });
      yield put({ type: 'setLoading', payload: { createLoading: false }});

      if (data.success) {
        message.success('创建成功', 3);
        browserHistory.push('/page/packetList');
        return;
      }
      message.error(data.msg || '系统错误，请重试', 3);
    },
    *modify({ payload }, { call, put }) {
      const { data } = yield call(createInteractiveService.modify, { payload });
      yield put({ type: 'setLoading', payload: { createLoading: false }});
      if (data.success) {
        message.success('更新成功', 3);
        browserHistory.push('/page/packetList');
        return;
      }
      message.error(data.msg || '系统错误，请重试', 3);
    },
    *fetch({ payload }, { call, put }) {
      const { data } = yield call(createInteractiveService.fetch, { payload });
      if (data) {
        const result = data.data;
        yield put({
          type: 'save',
          payload: {
            ...result
          }
        })
      }
    }
  },
  subscriptions: {
    setup({ dispatch, history }) {
      return history.listen(({ pathname, query }) => {
        const edit = pathToRegexp('/page/packet/edit/1/:id').exec(pathname);
        dispatch({
          type: 'setAction',
          payload: {
            createLoading: false,
            action: ''
          }
        });

        if (edit) {
          dispatch({
            type: 'fetch',
            payload: JSON.stringify({
              id: edit[1]
            })
          });
          dispatch({
            type: 'setAction',
            payload: {
              action: 'edit'
            }
          })
        }
      })
    }
  }
};
